﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using Slam.FieldTypes;
using Slam.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using System.Collections;
using System.Reflection;
using Slam.Events;
using Slam.Configuration;
using System.Threading;
using Slam;

namespace SlamCms.SharePoint.Publishing.CustomActions
{
	[ToolboxData("<{0}:PublishButton runat=\"server\" />")]
	public class PublishButton : SaveButton
	{
		public PublishButton()
		{
			this.ControlMode = SPControlMode.Edit;
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			//Slam.SlamContext.Get(List).Actions.Register(SlamEvent.PostSave, 10, listItem => Publish());
		}

		protected override bool SaveItem()
		{
			EventUtility eventUtility = new EventUtility();
			string previousFolderName = "";
			eventUtility.DisableEventHandlers();
			bool setStatus = true;
			if (base.List.EnableModeration && List.BaseType != SPBaseType.DocumentLibrary)
			{
				this.ListItem.ModerationInformation.Status = SPModerationStatusType.Approved;
				setStatus = false;
				eventUtility.EnableEventHandlers();
			}
			else if (base.List.EnableModeration && List.BaseType == SPBaseType.DocumentLibrary)
			{
				try
				{
					if (ListItem.Folder != null)
					{
						previousFolderName = ListItem.Folder.Name;
					}
				}
				catch { }
			}
			
			bool success = base.SaveItem();
			if (success && setStatus)
			{
				eventUtility.EnableEventHandlers();
				SPListItem listItem = SPContext.Current.List.GetItemById(SPContext.Current.ListItem.ID);
				if (List.BaseType == SPBaseType.DocumentLibrary && listItem.File != null && listItem.File.CheckOutType != SPFile.SPCheckOutType.None)
				{
					listItem.File.CheckIn("SlamCMS - Publish Item");
					Thread.Sleep(500);
					listItem = SPContext.Current.List.GetItemById(SPContext.Current.ListItem.ID);
				}
				listItem.ModerationInformation.Status = SPModerationStatusType.Approved;

				bool wait = false;
				if (base.List.EnableModeration && List.BaseType == SPBaseType.DocumentLibrary && !String.IsNullOrEmpty(previousFolderName))
				{
					SlamItemContext.FolderNameChanged = !previousFolderName.Equals(ListItem.Folder.Name);
					wait = true;
				}
				listItem.Update();
				if (wait)
					Thread.Sleep(500);
			}
			return success;
		}

		protected void Publish()
		{
			if (Page.Request.Params["__EVENTTARGET"].Contains("publishAndSaveButton") && base.List.EnableModeration)
			{
				SPListItem listItem = SPContext.Current.List.GetItemById(SPContext.Current.ListItem.ID);
				listItem.SetSlamProperty("SynchronousUpdate", true);
				EventUtility eventUtility = new EventUtility();
				eventUtility.DisableEventHandlers();
				listItem.SystemUpdate(false);
				listItem.ModerationInformation.Status = SPModerationStatusType.Approved;
				listItem.Update();
				eventUtility.EnableEventHandlers();
				if (List.BaseType == SPBaseType.DocumentLibrary)
				{
					Thread.Sleep(500);
					listItem = SPContext.Current.List.GetItemById(SPContext.Current.ListItem.ID);
				}
				listItem.SlamUpdate(true, false, false, SPContext.Current.Web.CurrentUser.LoginName, false);
			}
		}

		protected override string DefaultTemplateName
		{
			get
			{
				return "SlamCMSPublishButton";
			}
		}
		
		public override bool Visible
		{
			[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
			get
			{
				bool visible = false;
				if (base.List != null)
				{
					if (base.List.EnableModeration)
					{
						visible = base.Visible;

						if (!base.List.DoesUserHavePermissions(SPBasePermissions.ApproveItems))
						{
							if (this.Controls[0].Controls[0] is Button)
							{
								(this.Controls[0].Controls[0] as Button).Enabled = false;
							}
							else if (this.Controls[0].Controls[1] is Button)
							{
								(this.Controls[0].Controls[1] as Button).Enabled = false;
							}
						}
					}                    
				}
				return visible;
			}

			[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
			set
			{
				base.Visible = value;
			}
		}
	}
}
